<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script>
	////////console.log('mq');
	$(function() {
		////////console.log('load');
		$
				.get(
						'getMqConfigList.action',
						function(data) {
							data = decodeURIComponent(data);
							data = $.parseJSON(data);
							for ( var index in data) {
								if (data[index].dispatch != null)
									data[index].bussinessCode = data[index].dispatch.tableNameEn;
							}
							if (true) {
								var columns = [
										{
											field : 'serviceNo',
											checkbox : true,
											width : 20
										},
										{
											field : 'serviceUrl',
											title : 'Url',
											width : 150
										},
										{
											field : 'queueName',
											title : '队列名称',
											width : 150
										},
										{
											field : 'bussinessCode',
											title : '表名',
											width : 150,
											align : 'center',
										},
										{
											field : 'enableFlag',
											title : '是否有效',
											width : 50
										},
										{
											field : 'sendSys',
											title : '发送系统',
											width : 100
										},
										{
											field : 'receiveSys',
											title : '接收系统',
											width : 100
										},
										{
											field : 'createTime',
											title : '创建时间',
											width : 100
										},
										{
											field : 'updateTime',
											title : '更新时间',
											width : 100
										},
										{
											field : 'createUserid',
											title : '创建人',
											width : 50
										},
										{
											field : 'updateUserid',
											title : '更新人',
											width : 50
										},
										{
											field : 'dispatch',
											title : '操作',
											width : 100,
											align : 'center',
											formatter : function(value, rec,
													index) {
												var html = '';
												if (value == null)
													return '';
												if (value.funRole == 'sender') {
													if (value.funTimerState == 'running')
														html = '<a class="timerBtn" href="javascript:void(0)" onclick="stop('
																+ index
																		.toString()
																+ ',this)">停止定时任务</a>';
													else if (value.funTimerState == 'stopped')
														html = '<a class="timerBtn" href="javascript:void(0)" onclick="start('
																+ index
																		.toString()
																+ ',this)">启动定时任务</a>';
												} else if (value.funRole == 'receiver') {
													if (value.funListenerState == 'running')
														html = '<a class="timerBtn" href="javascript:void(0)" onclick="stopListener('
																+ index
																		.toString()
																+ ',this)">停止监听</a>';
													else if (value.funListenerState == 'stopped')
														html = '<a class="timerBtn" href="javascript:void(0)" onclick="startListener('
																+ index
																		.toString()
																+ ',this)">启动监听</a>';
												}
												return html;
											}
										} ];
								$('#config_list_div').datagrid({
									pagination : true,
									rownumbers : true,
									striped : true,
									height : 400,
									singleSelect : true,
									columns : [ columns ],
									toolbar : [ {
										text : '增加',
										iconCls : 'icon-add',
										handler : function() {
											changeToInsertMode();
										}
									}, {
										text : '新增并复制当前项',
										iconCls : 'icon-remove',
										handler : function() {
											changeToInsertModeAndCopyCurrent();
										}
									}, {
										text : '删除',
										iconCls : 'icon-remove',
										handler : function() {
											deleteConfig();
										}
									}, {
										text : '配置',
										iconCls : 'icon-edit'
									} ],
									onSelect : function(rowIndex, rowData) {
										onRowSelected(rowIndex, rowData);
									}
								});
								$('#config_list_div')
										.datagrid('loadData', data);
							}
						})
	});

	function reloadConfigList() {
		$
				.get(
						'getMqConfigList.action',
						function(data) {
							data = decodeURIComponent(data);
							data = $.parseJSON(data);
							for ( var index in data) {
								if (data[index].dispatch != null)
									data[index].bussinessCode = data[index].dispatch.tableNameEn;
							}
							$('#config_list_div').datagrid('loadData', data);
							formData = null;
						});
	}

	function onRowSelected(rowIndex, rowData) {
		//////console.log('rowSelected: ' + rowIndex);
		//////console.log(rowData);
		formData = {
			mqConfig : rowData
		};
		changeToUpdateMode();
	}

	function changeToUpdateMode() {
		loadFormData(formData);
		currentMode = 'update';
		$('#save_btn .icon-save').html('保存修改');
	}

	function changeToInsertMode() {
		$('#config_detail_form :input').each(function() {
			if ($(this).attr('type') == 'checkbox') {
				$(this).attr('checked', false);
			} else {
				$(this).val('');
			}
		});
		currentMode = 'insert';
		$('#save_btn .icon-save').html('保存新增');
	}

	function changeToInsertModeAndCopyCurrent() {
		$('#config_detail_form :input[name="mqConfig.serviceNo"]').val('');
		currentMode = 'insert';
		$('#save_btn .icon-save').html('保存新增');
	}

	var formData = null;
	var currentMode = null;

	function loadFormData(formData) {
		$('#config_detail_form :input').each(function() {
			var arr = $(this).attr('name').split('.');
			//////console.log(arr);
			var val = formData;
			for ( var property in arr) {

				if (val == null) {
					break;
				}
				val = val[arr[property]];
			}
			if ($(this).attr('type') == 'checkbox') {
				if (val == 'running')
					$(this).attr('checked', true);
			} else
				$(this).val(val);
		});
	}

	function start(index, dom) {
		//////console.log('start');
		var selectedRow = $('#config_list_div').datagrid('getRows')[index];
		var parameters = {
			'mqConfig.serviceNo' : selectedRow.serviceNo
		};
		$.post('startTimer.action', parameters, function(data) {
			$(dom).html('停止定时任务');
			$(dom).unbind('click');
			$(dom).click(function() {
				stop(index, dom);
			});
		});
	}

	function stop(index, dom) {
		//////console.log('stop');
		var selectedRow = $('#config_list_div').datagrid('getRows')[index];
		var parameters = {
			'mqConfig.serviceNo' : selectedRow.serviceNo
		};
		$.post('stopTimer.action', parameters, function(data) {
			$(dom).html('启动定时任务');
			$(dom).unbind('click');
			$(dom).click(function() {
				start(index, dom);
			});
		});
	}

	function startListener(index, dom) {
		//////console.log('startListener');
		var selectedRow = $('#config_list_div').datagrid('getRows')[index];
		var parameters = {
			'mqConfig.serviceNo' : selectedRow.serviceNo
		};
		$.post('startListener.action', parameters,
				function(data) {
					$(dom).html('停止监听');
					$(dom).unbind('click');
					$(dom).click(function() {
						stopListener(index, dom);
					});
				});
	}

	function stopListener(index, dom) {
		//////console.log('stop');
		var selectedRow = $('#config_list_div').datagrid('getRows')[index];
		var parameters = {
			'mqConfig.serviceNo' : selectedRow.serviceNo
		};
		$.post('stopListener.action', parameters,
				function(data) {
					$(dom).html('启动监听');
					$(dom).unbind('click');
					$(dom).click(function() {
						startListener(index, dom);
					});
				});
	}

	function save() {
		if (currentMode == 'update') {
			update();
		} else if (currentMode == 'insert') {
			insert();
		}
	}

	function update() {
		//////console.log('updateBegin');
		var submitData = {};
		$('#config_detail_form :input').each(function() {
			if ($(this).attr('type') == 'checkbox') {
				if ($(this).attr('checked') == 'checked')
					submitData[$(this).attr('name')] = 'running';
				else
					submitData[$(this).attr('name')] = 'stopped';
			} else {
				submitData[$(this).attr('name')] = $(this).val();
			}
		});
		loadFromForm(formData, null, submitData);
		////////console.log(submitData);
		$.post('updateMqConfig.action', submitData, function(
				data) {
			////////console.log('Save success');
			alert('Save && restart Successfully');
			reloadConfigList();
		});
	}

	function insert() {
		//////console.log('insertBegin');
		var submitData = {};
		$('#config_detail_form :input').each(function() {
			if ($(this).attr('type') == 'checkbox') {
				if ($(this).attr('checked') == 'checked')
					submitData[$(this).attr('name')] = 'running';
				else
					submitData[$(this).attr('name')] = 'stopped';
			} else {
				submitData[$(this).attr('name')] = $(this).val();
			}
		});
		loadFromForm(formData, null, submitData);
		////////console.log(submitData);
		$.post('insertMqConfig.action', submitData, function(
				data) {
			////////console.log('Save success');
			alert('Save && restart Successfully');
			reloadConfigList();
		});
	}

	function deleteConfig() {
		if (formData == null) {
			alert('请选中一个待删除项');
			return;
		}
		var submitData = {};
		loadFromForm(formData, null, submitData);
		$.post('deleteMqConfig.action', submitData, function(
				data) {
			////////console.log('Save success');
			alert('Save && restart Successfully');
			reloadConfigList();
		});
	}

	function testSql() {
		//////console.log('testSqlBegin');
		var submitData = {};
		$('#config_detail_form :input').each(function() {
			if ($(this).attr('type') == 'checkbox') {
				if ($(this).attr('checked') == 'checked')
					submitData[$(this).attr('name')] = 'running';
				else
					submitData[$(this).attr('name')] = 'stopped';
			} else {
				submitData[$(this).attr('name')] = $(this).val();
			}
		});
		////////console.log(submitData);
		$.post('mqTestSql.action', submitData, function(data) {
			var strData = data;
			data = decodeURIComponent(strData);
			data = $.parseJSON(data);
			if (data['error'] == null || data['error'] == undefined) {
				//////console.log(strData);
				$('#result_generator_window').window({
					width : 600,
					height : 400,
					modal : true,
					title : 'Result List'
				});
				$('#result_generator_window').css('display', '');
				resultGenerator.generateResult(data.data, 'sql_list_div');
				$('#sql_json_div').html(strData);
			} else {
				alert(data['error']);
			}
		});
	}

	function loadFromForm(parentObj, parentStr, submitData) {
		////////console.log(parentObj);
		if (parentObj == null)
			return;
		for ( var prop1 in parentObj) {
			var newStr = null;
			if (parentStr == null || parentStr == '') {
				newStr = prop1;
			} else
				newStr = parentStr + '.' + prop1;
			if (submitData[newStr] == null && !is(parentObj[prop1], 'Object')
					&& parentObj[prop1] != null)
				submitData[newStr] = parentObj[prop1];
			if (is(parentObj[prop1], 'Object') || is(parentObj[prop1], 'Array'))
				loadFromForm(parentObj[prop1], newStr, submitData);
		}
	}

	var resultGenerator = {
		generateList : function(data, containerId) {
			if (data.length > 0) {
				var columns = [];
				var tempData = data[0];
				for ( var property in tempData) {
					var column = {};
					column.field = property;
					column.title = property;
					column.width = 100;
					columns[columns.length] = column;
				}
				$('#' + containerId).datagrid({
					pagination : true,
					columns : [ columns ]
				});
				$('#' + containerId).datagrid('loadData', data);
			}
		},
		generateObject : function(data, containerId) {
			var propertyArray = propertyFormatter.formatObject(data);
			$('#' + containerId).propertygrid({
				showGroup : true
			});
			$('#' + containerId).propertygrid('loadData', propertyArray);
		},
		generateResult : function(data, containerId) {
			if (is(data, 'Object')) {
				resultGenerator.generateObject(data, containerId)
			} else if (is(data, 'Array')) {
				resultGenerator.generateList(data, containerId);
			} else
				alert('Return Data Invalid');
		}
	}

	var propertyFormatter = {
		formatObject : function(data) {
			var result = {};
			var rows = [];
			for ( var property in data) {
				var row = {};
				row.name = property;
				row.value = data[property];
				row.group = 'Property';
				row.editor = 'text';
				rows[rows.length] = row;
			}
			result.total = rows.length;
			result.rows = rows;
			return result;
		},
		formatObjectTreeLoop : function(data, parentId, rows) {
			for ( var property in data) {
				var index = rows.length + 1;
				var row = {};
				row.name = property;
				row.value = data[property];
				if (parentId != 0) {
					row._parentId = parentId;
				}
				row.id = index;
				rows[rows.length] = row;
				if (is(data[property], 'Object') || is(data[property], 'Array'))
					propertyFormatter.formatObjectTreeLoop(data[property],
							row.id, rows)

			}
		},
		formatObjectTree : function(data) {
			var result = {};
			var rows = [];
			propertyFormatter.formatObjectTreeLoop(data, 0, rows);
			result.total = rows.length;
			result.rows = rows;
			return result;
		}
	}

	var is = function(obj, type) {
		return (type === "Null" && obj === null)
				|| (type === "Undefined" && obj === void 0)
				|| (type === "Number" && isFinite(obj))
				|| Object.prototype.toString.call(obj).slice(8, -1) == type;
	};
</script>

<div id="config_list_div"></div>
<div style="width: 100%; height: 20"></div>
<div id="config_detail_div">
	<div class="toolbar">
		<a id="save_btn" href="javascript:void(0)"
			class="easyui-linkbutton l-btn" iconcls="icon-save"
			onclick="javascript:save()">保存</a> <a id="reset_btn"
			href="javascript:void(0)" class="easyui-linkbutton l-btn"
			iconcls="icon-undo">重置</a>
	</div>
	<form id="config_detail_form">
		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td width="7" bgcolor="#E8EEF5">&nbsp;</td>
				<td width="24" align="center" bgcolor="#E8EEF5"><img
					src="images/arrow_02.jpg" width="16" height="16">
				</td>
				<td height="35" align="left" bgcolor="#E8EEF5" class="area_Title">
					基本设置</td>
				<td width="112" align="right" bgcolor="#E8EEF5" class="black12">
					<img id="img0" src="images/min.jpg"
					onclick="javascript:turnit('i0','img0');" width="11" height="11">
				</td>
				<td width="10" align="center" bgcolor="#E8EEF5" class="black12">
					&nbsp;</td>
			</tr>
		</table>
		<table width="100%">
			<tr>
				<td class="formTitle">NO</td>
				<td class="formInfo" colspan="3"><input
					name="mqConfig.serviceNo" disabled="disabled" />
				</td>
			</tr>
			<tr>
				<td class="formTitle">Url</td>
				<td class="formInfo"><input name="mqConfig.serviceUrl" />
				</td>
				<td class="formTitle">队列名称</td>
				<td class="formInfo"><input name="mqConfig.queueName" />
				</td>
			</tr>
			<tr>
				<td class="formTitle">用户名</td>
				<td class="formInfo"><input name="mqConfig.userName" />
				</td>
				<td class="formTitle">密码</td>
				<td class="formInfo"><input name="mqConfig.password"
					type="password" />
				</td>
			</tr>
			<tr>
				<td class="formTitle">发送模式</td>
				<td class="formInfo"><select name="mqConfig.sendMode">
						<option value="QUEUE">点对点</option>
						<option value="TOPIC">广播</option>
				</select>
				</td>
				<td class="formTitle">持久化模式</td>
				<td class="formInfo"><select name="mqConfig.deliveryMode">
						<option value="PERSISTENT">持久化</option>
						<option value="NON_PERSISTENT">非持久化</option>
				</select>
				</td>
			</tr>
			<tr>
				<td class="formTitle">持久化有效期</td>
				<td class="formInfo" colspan="3"><input
					name="mqConfig.timeToAlive" />
				</td>
			</tr>
			<tr>
				<td class="formTitle">是否有效</td>
				<td class="formInfo" colspan="3"><select
					name="mqConfig.enableFlag">
						<option value="1">是</option>
						<option value="0">否</option>
				</select>
				</td>
			</tr>
			<tr>
				<td class="formTitle">发送系统</td>
				<td class="formInfo"><input name="mqConfig.sendSys" />
				</td>
				<td class="formTitle">接收系统</td>
				<td class="formInfo"><input name="mqConfig.receiveSys" />
				</td>
			</tr>
			<tr>
				<td class="formTitle"></td>
				<td class="formInfo"></td>
				<td class="formTitle"></td>
				<td class="formInfo"></td>
			</tr>
		</table>
		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td width="7" bgcolor="#E8EEF5">&nbsp;</td>
				<td width="24" align="center" bgcolor="#E8EEF5"><img
					src="images/arrow_02.jpg" width="16" height="16">
				</td>
				<td height="35" align="left" bgcolor="#E8EEF5" class="area_Title">
					高级设置</td>
				<td width="112" align="right" bgcolor="#E8EEF5" class="black12">
					<img id="img0" src="images/min.jpg"
					onclick="javascript:turnit('i0','img0');" width="11" height="11">
				</td>
				<td width="10" align="center" bgcolor="#E8EEF5" class="black12">
					&nbsp;</td>
			</tr>
		</table>

		<table width="100%">
			<tr>
				<td class="formTitle">角色</td>
				<td class="formInfo"><select name="mqConfig.dispatch.funRole">
						<option value="sender">发送方</option>
						<option value="receiver">接收方</option>
				</select>
				</td>
				<td class="formTitle">执行类型</td>
				<td class="formInfo"><select name="mqConfig.dispatch.funType">
						<option value="sql">SQL</option>
						<option value="bussiness">业务方法</option>
						<option value="both">SQL & Bussiness</option>
				</select>
				</td>
			</tr>
			<tr>
				<td class="formTitle"></td>
				<td class="formInfo"></td>
				<td class="formTitle"></td>
				<td class="formInfo"></td>
			</tr>
		</table>
		<div class="fieldset flash" align="left" style="width: 100%;">
			<span class="legend" style="font: 700 11px Helvetica, sans-serif;">数据库设置</span>
			<div>
				<table width="100%">
					<tr>
						<td class="formTitle">连接字符串</td>
						<td class="formInfo" colspan="3"><textarea
								name="mqConfig.dispatch.connectStr" style="width: 200px"></textarea>

						</td>

					</tr>

					<tr>
						<td class="formTitle">表名称</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.tableNameEn" />
						</td>
						<td class="formTitle">源表名称</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.sourceTableName" />
						</td>
					</tr>

					<tr>
						<td class="formTitle">数据库用户名</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.databaseUserName" />
						</td>
						<td class="formTitle">数据库密码</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.databasePassword" type="password" />
						</td>
					</tr>
					<tr>

						<td class="formTitle">SQL语句</td>
						<td class="formInfo" colspan="3"><textarea
								name="mqConfig.dispatch.funSql" style="width: 50%; height: 80px"></textarea>
							<a href="javascript:void(0)" onclick="testSql();return false;">测试SQL
								</button>
						</td>
					</tr>
				</table>
			</div>
		</div>
		<div class="fieldset flash" align="left" style="width: 100%;">
			<span class="legend" style="font: 700 11px Helvetica, sans-serif;">定时器设置</span>
			<div>
				<table width="100%">
					<tr>
						<td class="formTitle">启动定时</td>
						<td class="formInfo" colspan="3"><input
							name="mqConfig.dispatch.funTimerState" type="checkbox" />
						</td>
					<tr>
						<td class="formTitle">开始时间</td>
						<td class="formInfo"><input class="Wdate"
							name="mqConfig.dispatch.funBeginTime"
							onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" />
						</td>
						<td class="formTitle">结束时间</td>
						<td class="formInfo"><input class="Wdate"
							name="mqConfig.dispatch.funEndTime"
							onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" />
						</td>
						<!-- <tr>

						<td class="formTitle">周期</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.funInterval" /></td>
						<td class="formTitle">最大次数</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.funMaxCount" /></td>
					</tr> -->
					<tr>

						<td class="formTitle">表达式</td>
						<td class="formInfo" colspan="3"><input
							name="mqConfig.dispatch.triggerCronExpression" />
						</td>
				</table>
			</div>
		</div>
		<div class="fieldset flash" align="left" style="width: 100%;">
			<span class="legend" style="font: 700 11px Helvetica, sans-serif;">监听设置</span>
			<div>
				<table width="100%">
					<tr>
						<td class="formTitle">启动监听</td>
						<td class="formInfo" colspan="3"><input
							name="mqConfig.dispatch.funListenerState" type="checkbox" />
						</td>
					<tr>
						<td class="formTitle">接收方数据库操作</td>
						<td class="formInfo"><select
							name="mqConfig.dispatch.receiverDbOp">
								<option value="insert">仅插入</option>
								<option value="all">所有更新</option>
						</select>
						</td>
						<td class="formTitle">递增字段</td>
						<td class="formInfo"><input
							name="mqConfig.dispatch.senderIncrementColumn" />
						</td>
					</tr>
				</table>
			</div>
		</div>
	</form>

</div>
<div id='result_generator_window' style="display:none">
	<div id="sqlResultTabs" class="easyui-tabs" tools="#tab-tools"
		width="100%" height="100%">
		<div id="sql_list_div" title="列表" tools="#p-tools"
			style="padding: 20px;"></div>
		<div id="sql_json_div" title=JSON " tools="#p-tools"
			style="padding: 20px;"></div>

	</div>
</div>
